package com.sysu.minsysu.wdzj;

import java.text.SimpleDateFormat;
import java.util.Date;

import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.Toast;

import com.minSYSU.db.Records;
import com.sysu.minsysu.R;
import com.sysu.minsysu.weibo.activity.WeiboMainAct;
import com.sysu.minsysu.weibo.utils.ConfigUtil;
import com.sysu.minsysu.zdkb.utils.AnimationTabHost;
import com.sysu.minsysu.zdkb.utils.SeekbarTime;



public class MinSYSUMessageActivity extends TabActivity implements OnTabChangeListener {
    /** Called when the activity is first created. */
	private GestureDetector gestureDetector;
	private FrameLayout frameLayout;

	private AnimationTabHost mTabHost;
	private TabWidget mTabWidget;
	private ListView list;
	private SeekBar seekBar;
	private Button btnAddMessage;
	private Button btnReset;
	private EditText content;
	private Spinner location;
	private CheckBox tongBuWeiBo;
	
	private SlidingDrawer Drawer;
	private Button btnRefresh;
	private Button btnNewMessage;
	private Button btnGetLocation;
	private Button btnTongbuweibo;
	private Button btnBack;
	
	public static String selectTime;
	public static String[] timeRange = new String[2];
	
	private SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");       
	private Date curDate; 
	private Records Record;
	private Intent intent = new Intent();

	/** 记录当前分页ID */
	private int currentTabID = 0;
	private int tag;
	
	public static int MODE = MODE_PRIVATE;
	
	private Weibo weibo;
	private com.szy.weibo.service.Weibo weibo2;
	private String accessToken;
	private String oauth_token_secret;
	private String userId;
	
	private String qq_accessToken;
	private String qq_oauth_token_secret;
	private String qq_userId;
	
	private static String TAG = "MinSYSUMessageActivity"; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_host_view);
		
		tag = getIntent().getFlags();
		Log.e("MinSYSUMessageActivity get tag", String.valueOf(tag));
		
		mTabHost = (AnimationTabHost) findViewById(android.R.id.tabhost);
		mTabWidget = (TabWidget) findViewById(android.R.id.tabs);
		seekBar = (SeekBar) findViewById(R.id.seekbar);		
		content = (EditText) findViewById(R.id.newmessage_content);
		location = (Spinner) findViewById(R.id.newmessage_loc);	 
		btnAddMessage = (Button) findViewById(R.id.newmessage_add);
		btnReset = (Button) findViewById(R.id.newmessage_reset);		 		
	 	tongBuWeiBo = (CheckBox) findViewById(R.id.newmessage_tongbu);
	 	btnRefresh = (Button) findViewById(R.id.button_refresh);
	 	btnNewMessage = (Button) findViewById(R.id.button_newmessage);
	 	btnGetLocation = (Button) findViewById(R.id.button_gps);
	 	btnTongbuweibo = (Button) findViewById(R.id.button_tongbuweibo);
	 	btnBack = (Button) findViewById(R.id.button_back);
	 	
	 	Drawer = (SlidingDrawer) findViewById(R.id.slidingdrawer_newmessage);
	 	
	 	btnAddMessage.setOnClickListener(buttonViewClickListener);
	 	btnReset.setOnClickListener(buttonViewClickListener);
	 	btnRefresh.setOnClickListener(buttonViewClickListener);
	 	btnNewMessage.setOnClickListener(buttonViewClickListener);
	 	btnGetLocation.setOnClickListener(buttonViewClickListener);
	 	btnTongbuweibo.setOnClickListener(buttonViewClickListener);
	 	btnBack.setOnClickListener(buttonViewClickListener);
	 	
	 	 //获取sina微博token和token_secret
        SharedPreferences sharedPreferences = getSharedPreferences("xinlang", MODE);
		accessToken = sharedPreferences.getString("oauth_token", null);
		oauth_token_secret = sharedPreferences.getString("oauth_token_secret", null);
		userId = sharedPreferences.getString("userId", "");		
		Log.d("userId", userId);
		Log.d(TAG, "accessToken: "+ accessToken);
		Log.d(TAG, "oauth_token_secret:" +oauth_token_secret);
		
		//获取qq微博token和token_secret
        sharedPreferences = getSharedPreferences("tengxun", MODE);
        qq_accessToken = sharedPreferences.getString("oauth_token", null);
        qq_oauth_token_secret = sharedPreferences.getString("oauth_token_secret", null);
        qq_userId = sharedPreferences.getString("userId", "");	
		Log.d("qq_userId", userId);
		Log.d(TAG, "qq_accessToken: "+ qq_accessToken);
		Log.d(TAG, "qq_oauth_token_secret:" +qq_oauth_token_secret);
		
		
		System.setProperty("weibo4j.oauth.consumerKey", ConfigUtil.getInstance().getSina_AppKey());
        System.setProperty("weibo4j.oauth.consumerSecret", ConfigUtil.getInstance().getSina_AppSecret());
        weibo = new Weibo();
        weibo.setToken(accessToken, oauth_token_secret);  
        
        weibo2 = new com.szy.weibo.service.Weibo();
	
		mTabHost.setOnTabChangedListener(this);

		init();
		
		if (tag == 2) {
			mTabHost.setCurrentTab(1);
		} else {
			mTabHost.setCurrentTab(0);
		}
		
		gestureDetector = new GestureDetector(new TabHostTouch());
		new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (gestureDetector.onTouchEvent(event)) {
					return true;
				}
				return false;
			}
		};

		frameLayout = mTabHost.getTabContentView();
		Log.i("TabHostActivity","TabHostActivity====>>>onCreate()===>>>>frameLayout: "
						+ frameLayout.getChildCount());
		
	}
		
	private View.OnClickListener buttonViewClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
				case R.id.newmessage_add:
					//是否联网
	    			ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
	    			NetworkInfo info = cwjManager.getActiveNetworkInfo(); 
	    			
	    			if (info != null && info.isAvailable()){
						//add record
						Record = new Records( "user", content.getText().toString(), formatter.format(curDate).toString(), location.getSelectedItem().toString());
						Log.e("new record",  " content:" + content.getText().toString()+
											" location:" + location.getSelectedItem().toString());
						MyMessage.db.AddRecords(Record);
						
						Log.e(TAG + " tongbuweibo?", String.valueOf(tongBuWeiBo.isClickable()));
						if (tongBuWeiBo.isClickable()) {
							if (isWeiboAuthorized()) {
								String msg = "我在" + location.getSelectedItem().toString() 
												+ ":" + content.getText().toString();
								sendWeibo(msg);	
							} else {
								showDialog();							
							}
							tongBuWeiBo.setClickable(false) ;
						}
	    			} else {    				
	    				Log.d(TAG, "无法连接网络!");
	    				Toast.makeText(MinSYSUMessageActivity.this, "无法连接网络!", Toast.LENGTH_SHORT).show();
	    			}    			    			
					
//					startActivity(intent);
//					MyMessage.db.close();
//					finish();
					break;
					
					
				case R.id.newmessage_reset:
					curDate = new Date(System.currentTimeMillis());//获取当前时间     					
					content.setText("");
					break;
				case R.id.button_refresh:
					curDate = new Date(System.currentTimeMillis());					
					/*
					 * to do
					 */
					break;
				case R.id.button_gps:
					/*
					 * to do
					 */
					break;
				case R.id.button_newmessage:
					if (!Drawer.isOpened()) {
						Drawer.open();
					} else {
						Drawer.close();
					}
					
					break;
				case R.id.button_tongbuweibo:
					intent.setClass(MinSYSUMessageActivity.this, WeiboMainAct.class);
					startActivity(intent);
					break;
				case R.id.button_back:
					MinSYSUMessageActivity.this.finish();
					break;
			}
			
		}
	};
	
	

	private void init() {
		setIndicator(R.drawable.tab_logo_0, 0, new Intent(this,
				MyMessage.class));
		setIndicator(R.drawable.tab_logo_1, 1, new Intent(this,
				ShowNewMessage.class));
//		setIndicator(R.drawable.tab_logo_2, 2, new Intent(this,
//				TabHostTestThree.class));
//		setIndicator(R.drawable.tab_logo_3, 3, new Intent(this,
//				TabHostTestFour.class));

		mTabHost.setOpenAnimation(true);
		
		//获取时间轴时间		
		seekBar.setMax(100);
		seekBar.setProgress(100);
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
				Log.v("onProgressChanged()", String.valueOf(progress) + ", " +String.valueOf(fromTouch));
				SeekbarTime seekbarTime = new SeekbarTime();
				selectTime = seekbarTime.changeSeekbarToTime(progress);
				Toast.makeText(MinSYSUMessageActivity.this, selectTime, Toast.LENGTH_SHORT).show();
										
				timeRange = seekbarTime.getRangeTime(selectTime);
//				Log.e("range time", timeRange[0] + " " + timeRange[1]);
//				MyMessage.myCursor = MyMessage.db.getRecordsByTime(timeRange[0], timeRange[1]);
				
			}
	
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				Log.v("onStartTrackingTouch()",String.valueOf(seekBar.getProgress()));
			}
	
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				Log.v("onStopTrackingTouch()",String.valueOf(seekBar.getProgress()));
			}
		});		
		
		//设置spinner
		 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.site, android.R.layout.simple_spinner_dropdown_item);
		 adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
		 location.setAdapter(adapter);
		 
		 curDate = new Date(System.currentTimeMillis());//获取当前时间     					
		 
		 intent.setClass(this, MinSYSUMessageActivity.class);
	}

	protected void showDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示")
			.setMessage("请设置要同步的微博")
			.setOnKeyListener( new DialogInterface.OnKeyListener() {			
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					if( keyCode==KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN ){
						finish();
						return true;
					}else {
						return false;
					}
				}
			}).setPositiveButton("确定", new DialogInterface.OnClickListener() {				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					intent.setClass(MinSYSUMessageActivity.this, WeiboMainAct.class);
					startActivity(intent);
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
	}

	protected boolean isWeiboAuthorized() {
		// TODO Auto-generated method stub
		if ((accessToken != null && oauth_token_secret != null)
				&& (qq_accessToken != null && qq_oauth_token_secret != null)) {
			return true;
		}
		return false;
	}

	private void setIndicator(int icon, int tabId, Intent intent) {

		View localView = LayoutInflater.from(this.mTabHost.getContext())
										.inflate(R.layout.wodeziji_tab_widget, null);
		((ImageView) localView.findViewById(R.id.activity_tab_image)).setBackgroundResource(icon);
//		LinearLayout tablayout;
//		tablayout = (LinearLayout) localView.findViewById(R.id.tablayout);
//		tablayout.setPadding(10, 20, 10, 20);
		

		String str = String.valueOf(tabId);

		TabHost.TabSpec localTabSpec = mTabHost.newTabSpec(str).setIndicator(
				localView).setContent(intent);
		mTabHost.addTab(localTabSpec);
	}

	@Override
	public void onTabChanged(String tabId) {
		int tabID = Integer.valueOf(tabId);
		
		if (tabID == 0) {
			seekBar.setVisibility(View.GONE);
		} else {
			seekBar.setVisibility(View.VISIBLE);
		}
		
		for (int i = 0; i < mTabWidget.getChildCount(); i++) {
			if (i == tabID) {
//				mTabWidget.getChildAt(Integer.valueOf(i)).setBackgroundColor(
//						Color.YELLOW);
				mTabWidget.getChildAt(Integer.valueOf(i)).setBackgroundResource(
						R.drawable.buttom1_change2);
			} else {
				mTabWidget.getChildAt(Integer.valueOf(i))
						.setBackgroundResource(R.drawable.main_meun_bg);
			}
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

		if (gestureDetector.onTouchEvent(event)) {
			event.setAction(MotionEvent.ACTION_CANCEL);
		}

		return super.dispatchTouchEvent(event);

	}

	private class TabHostTouch extends SimpleOnGestureListener {
		// 滑动翻页所需距离 
		private static final int ON_TOUCH_DISTANCE = 150;

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (e1.getX() - e2.getX() <= (-ON_TOUCH_DISTANCE)) {
				currentTabID = mTabHost.getCurrentTab() - 1;

				if (currentTabID < 0) {
					currentTabID = mTabHost.getTabCount() - 1;
				}
			} else if (e1.getX() - e2.getX() >= ON_TOUCH_DISTANCE) {
				currentTabID = mTabHost.getCurrentTab() + 1;

				if (currentTabID >= mTabHost.getTabCount()) {
					currentTabID = 0;
				}
			}
			mTabHost.setCurrentTab(currentTabID);
			return false;
		}
	}
	
	private void sendWeibo(String arg){
		//发送sina微博 
		if (accessToken != null && oauth_token_secret != null) {
			try{						    				
				weibo.updateStatus(arg);
				Toast.makeText(MinSYSUMessageActivity.this, "微博发送成功", Toast.LENGTH_SHORT).show();
			}catch (WeiboException e){
				Toast.makeText(MinSYSUMessageActivity.this, "微博发送失败", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}	
		}
		//发送qq微博 
		if (qq_accessToken != null && qq_oauth_token_secret != null) {
			String result = "" ;
			result = weibo2.add(qq_accessToken, qq_oauth_token_secret, "json", arg, "127.0.0.1");
			Log.i(TAG, result);
		}
	}
}